<template>
  <div class="user-info">
    <el-dropdown @command="handleCommand">
      <span class="user-dropdown-link">
        <el-icon class="user-icon"><user-filled /></el-icon>
        <span class="username">{{ userName }}</span>
        <el-icon class="el-icon--right"><arrow-down /></el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="logout">
            <el-icon><switch-button /></el-icon>
            <span style="margin-left: 5px;">退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowDown, UserFilled, SwitchButton } from '@element-plus/icons-vue'

const router = useRouter()
const userName = ref('未登录')

// 获取用户信息
onMounted(() => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      userName.value = user.name || user.username || '未知用户'
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
})

// 处理下拉菜单命令
function handleCommand(command) {
  if (command === 'logout') {
    handleLogout()
  }
}

// 退出登录
function handleLogout() {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    ElMessage.success('退出登录成功')
    router.push('/login')
  }).catch(() => {})
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown-link {
  display: flex;
  align-items: center;
  color: #fff;
  cursor: pointer;
}

.user-icon {
  font-size: 20px;
  margin-right: 8px;
  color: #fff;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 5px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.username {
  font-size: 16px;
  margin-right: 5px;
}
</style> 